<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\index\model\Applet as AppletModel;
use think\Session;

/**
 * 用户小程序
 */
class Applet extends Frontend
{
    protected $layout = 'user';
    protected $noNeedRight = ['*'];

    /**
     * 列表
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $model = new AppletModel;
        $list = $model->getList($user['id']);
        $this->view->assign('title', __('My applet'));
        return $this->view->fetch('index',compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $app_type = $this->request->post('app_type');
            $model = new AppletModel;
            if ($model->add([
                'app_type' => $app_type,
                'user_id' => $user['id']
            ])) {
                $this->success(__('Operation completed'), url('applet/index'));
            } else {
                $error = $model->getError() ?: __('Operation failed');
                $this->error($error);
            }
        }
        $this->view->assign('title', __('Add applet'));
        return $this->view->fetch();
    }

    /**
     * 小程序管理登录
     */
    public function login($applet_id)
    {   
        $wxapp = AppletModel::get($applet_id);
        if($wxapp['app_type'] == 10){
            $session_name = 'hema_wxsaas';
            empty($wxapp['app_name']) && $wxapp['app_name'] = '微信小程序';
            $url = '/store/wxsaas/wxapp/index';
        }
        if($wxapp['app_type'] == 20){
            $session_name = 'hema_wxsaas';
            empty($wxapp['app_name']) && $wxapp['app_name'] = '微信公众号';
            $url = '/store/wxsaas/wechat/index';
        }
        // 验证用户名密码是否正确
        if($user = $this->auth->getUser()){
            // 保存登录状态
            Session::set($session_name, [
                'user' => $user->toArray(),
                'applet_id' => $applet_id,
                'app_type' => $wxapp['app_type'],
                'app_name' => $wxapp['app_name'],
                'is_login' => true,
            ]);
            $this->success('正在跳转...', $url);
        }else{
            $this->error('登录失败, 用户名或密码错误');
        }
    }

    /**
     * 退出登录
     */
    public function logout($app_type)
    {
        if($app_type < 21){
            $session_name = 'hema_wxsaas';
        }
        Session::clear($session_name);
        $this->redirect(url('user/index'));
    }

}
